import createError = require('http-errors');
import express = require('express');
import path = require('path');
import cookieParser = require('cookie-parser');
import logger = require('morgan');
var bodyParser = require('body-parser')
const jwt = require('jsonwebtoken');
const compression = require('compression');

// 入口文件 检测是否登录 token
import indexRouter from './routes/index';
import upload from "./routes/up"
import MYSQL from "./libs/sqlcmd/mysql";
import { log } from 'console';
const config = require("config-lite")(__dirname);
let mysql = new MYSQL(config.mysql);
const app = express();
const data_ret = require('./libs/ret_data.json');
import rds from "./libs/redis/redis"
let cli = new rds(config.redis.host, config.redis.port, config.redis.password);

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// 预处理路由配置
const urlRouter = require('./config/router_x.js');
const preprocessRoutes = (routes) => {
  return routes.map(route => {
    const pattern = route.url.replace(/\*/g, '*');
    return {
      ...route,
      regex: new RegExp(`^${pattern}$`)
    };
  });
};
const processedUrlRouter = preprocessRoutes(urlRouter);

// 基础中间件
app.use(logger('dev'));
app.use(express.json({ limit: "200000kb" }));
app.use(bodyParser.json({ limit: '100000kb' }));
app.use(bodyParser.urlencoded({
  limit: '100000kb',
  extended: true,
  parameterLimit: 500000,
}));
app.use(cookieParser());
app.use(compression());

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));
app.use('/up', express.static('up'));
express.static.mime.define({ 'application/msword': ['doc'] });
express.static.mime.define({ 'application/pdf': ['pdf'] });

// 认证中间件
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type,token');
  res.header('Access-Control-Allow-Methods', '*');
  
  if (processedUrlRouter.some(route => route.regex.test(req.path))) {
    next();
  } else {
    const token = req.headers.token;
    if (!token) {
      data_ret.code = 402;
      data_ret.msg = '未登录';
      data_ret.icon = "error";
      return res.json(data_ret);
    }

    jwt.verify(token, config.jwt.secret, async (err, decoded) => {
      if (err) {
        data_ret.code = 401;
        data_ret.msg = err.name === 'TokenExpiredError' ? '登录已过期' : '无效登录';
        data_ret.icon = "error";
        return res.json(data_ret);
      }
      let token_user = await cli.hget("wg_users", decoded.id);
      if (token_user != token) {
        data_ret.code = 401;
        data_ret.msg = "登录凭证错误！";
        data_ret.icon = "error";
        return res.json(data_ret);
      }
      res.locals.userinfo = decoded;
      next();
    });
  }
});

// 路由注册
app.use('/login', indexRouter);
app.use("/upload", upload);

// 错误处理
app.use(function (req, res, next) {
  next(createError(404));
});

app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;